//
//  CapitalFilterViewController.swift
//  jiaoyi
//
//  Created by 易万军 on 2018/10/21.
//  Copyright © 2018 wjk. All rights reserved.
//

import UIKit
import Moya
import SwiftyJSON

class CapitalFilterViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    private var type = 0
    private var direction = 0
    private var startDate: Date?
    private var endDate: Date?
    
    private var datePicker: UIDatePicker!
    
    @IBOutlet weak var buttonContainer: UIView!
    @IBOutlet weak var startTextField: UITextField!
    @IBOutlet weak var endTextfield: UITextField!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    
    
    var t1:JSON = JSON(["business_type_text":"全部","business_type":""])
    var t2:JSON = JSON(["business_type_text":"全部","business_type":""])
    
    var data:[[JSON]] = [[JSON]]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupDataPiker()
        self.collectionView.register(R.nib.rightCollectionViewCell(), forCellWithReuseIdentifier: "RightCollectionViewCell")
        self.collectionView.register(RightHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "RightHeader")
        loadData()
        // Do any additional setup after loading the view.
    }
    
    func loadData() {
        
        
        NetWorkRequest(.bType()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                
                var d1 = [JSON]()
                d1.append(JSON(["business_type_text":"全部","business_type":""]))
                JSON(res as Any)["data"]["business_types"].arrayValue.forEach({ (r) in
                    d1.append(r)
                })
                
                self.data.append(d1)
                
                var d2 = [JSON]()
                d2.append(JSON(["business_type_text":"全部","business_type":""]))
                d2.append(JSON(["business_type_text":"收入","business_type":"1"]))
                d2.append(JSON(["business_type_text":"支出","business_type":"2"]))
                d2.append(JSON(["business_type_text":"内转","business_type":"3"]))
                self.data.append(d2)
                self.collectionView.reloadData()
            }
        }
        
    }
    
    func setupDataPiker(){
        datePicker = UIDatePicker(frame: CGRect.zero)
        datePicker.locale = NSLocale.init(localeIdentifier: "zh") as Locale
        datePicker.datePickerMode = .date
        datePicker.setDate(Date(), animated: true)
        datePicker.addTarget(self, action: #selector(datePickerChanged(_:)), for: .valueChanged)
        startTextField.inputView = datePicker
        endTextfield.inputView = datePicker
        startTextField.delegate = self
        endTextfield.delegate = self
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: deviceWidth(), height: 30)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: collectionView.bounds.size.width/3, height: 80)
    }
    
    //设定header和footer的方法，根据kind不同进行不同的判断即可
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader{
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "RightHeader", for: indexPath) as! RightHeader
            if indexPath.section == 0 {
                headerView.label.text = "业务类型"
            }else {
                headerView.label.text = "方向"
            }
            
            return headerView
        }
        return UICollectionReusableView()
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data[section].count
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RightCollectionViewCell", for: indexPath) as! RightCollectionViewCell
        
        let j = data[indexPath.section][indexPath.row]
        
        cell.btn.setTitle(j["business_type_text"].stringValue, for: .normal)
        cell.btn.setTitleColor(kRGBColorFromHex(rgbValue: 0x333333), for: .normal)
        cell.btn.backgroundColor = kRGBColorFromHex(rgbValue: 0xf3f3f3)
        
        viewRadius(cor: 5, img: cell.btn)
        
        
        
        if indexPath.section == 0 {
            if j["business_type_text"].stringValue == t1["business_type_text"].stringValue {
                cell.btn.setTitleColor(kRGBColorFromHex(rgbValue: 0x50a3f8), for: .normal)
                viewBorderRadius(cor: 5, img: cell.btn, with: 1, color: kRGBColorFromHex(rgbValue: 0x50a3f8))
                cell.btn.backgroundColor = kRGBColorFromHex(rgbValue: 0xedf7ff)
            }
        }else {
            if j["business_type_text"].stringValue == t2["business_type_text"].stringValue {
                cell.btn.setTitleColor(kRGBColorFromHex(rgbValue: 0x50a3f8), for: .normal)
                viewBorderRadius(cor: 5, img: cell.btn, with: 1, color: kRGBColorFromHex(rgbValue: 0x50a3f8))
                cell.btn.backgroundColor = kRGBColorFromHex(rgbValue: 0xedf7ff)
            }
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            t1 = data[0][indexPath.row]
        }else {
            t2 = data[1][indexPath.row]
        }
        collectionView.reloadData()
    }
    

    @objc func datePickerChanged(_ sender: UIDatePicker){
        let dateStr = dateToString(datePicker.date)
        if startTextField.isFirstResponder {
            startTextField.text = dateStr
        }
        if endTextfield.isFirstResponder {
            endTextfield.text = dateStr
        }
    }
    
    func dateToString(_ date: Date?) -> String?{
        
        let dateformater = DateFormatter(withFormat: "yyyy-MM-dd", locale: "zh")
        if let date = date{
            return dateformater.string(from: date)
        }
        return nil
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    @IBAction func resetAction(_ sender: Any) {
        //业务类型
        if let oldTypeButton = buttonContainer.viewWithTag(1000 + type) as? UIButton{
            oldTypeButton.isSelected = false
        }
        //方向
        if let oldTypeButton = buttonContainer.viewWithTag(2000 + direction) as? UIButton{
            oldTypeButton.isSelected = false
        }
        //业务类型
        if let button = buttonContainer.viewWithTag(1000) as? UIButton{
            button.isSelected = true
            type = 0
        }
        //方向
        if let button = buttonContainer.viewWithTag(2000) as? UIButton{
            button.isSelected = true
            direction = 0
        }
        
        startTextField.text = nil
        endTextfield.text = nil
        startDate =  nil
        endDate = nil
        t1 = JSON(["business_type_text":"全部","business_type":""])
        t2 = JSON(["business_type_text":"全部","business_type":""])
        collectionView.reloadData()
        
    }
    
    @IBAction func commitAction(_ sender: Any) {
        
        
        NotificationCenter.default.post(name: NSNotification.Name.rightRef1, object: ["operation_time_begin":startTextField.text!, "operation_time_end":endTextfield.text!,"direction":t2["business_type"].stringValue,"business_type":t1["business_type"].stringValue])
        
    }
    
    func showDatePicker(){
        let datePicker = UIDatePicker(frame: CGRect.zero)
        startTextField.inputView = datePicker
        
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension CapitalFilterViewController: UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return false
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        let dateStr = dateToString(datePicker.date)
        textField.text = dateStr
        
        if textField == startTextField {
            startDate = datePicker.date
        }
        if textField == endTextfield{
            endDate = datePicker.date
        }
        
        return true
    }
}
